package com.dhl.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 实现redis加减原子操作
 *
 * @author YHS
 */
@Component
public class RedisLockUtils {
    /**
     * 锁标志
     */
    private String lockKey = "lock";
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 尝试获取锁
     * @param requestId
     * @param expireTime
     * @return 是否成功？
     */
    public Boolean getLock(String requestId, int expireTime) {
        // 绑定一个key对象
        BoundValueOperations<String, String> operations = stringRedisTemplate.boundValueOps(lockKey);
        String value = operations.get();
        while (true) {
            // 加锁
            if (operations.setIfAbsent(requestId, expireTime, TimeUnit.SECONDS)) {
                return true;
            }
            if (StringUtils.hasLength(value) && requestId.equals(value)){
                return true;
            }
        }
    }

    /**
     * 释放锁
     * @param requestId
     * @return 释放成功？
     */
    public boolean releaseLock(String requestId) {
        String script = " if redis.call ('get',KEYS[1]) == ARGV[1] then " + " return redis.call('del', KEYS[1]) " + " else return 0 end ";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
        Long execute = stringRedisTemplate.execute(redisScript, Collections.singletonList(lockKey), requestId);
        Long lockFlag = 1L;
        return lockFlag.equals(execute);
    }

    /**
     * 锁续期
     * @param time 续期时间
     * @param requestId uuid---唯一标识
     * @return 线程对象
     */
    public Thread createLifeThread(int time, String requestId) {
        return new Thread(() -> {
            while (true) {
                try {
                    TimeUnit.SECONDS.sleep(time * 2 / 3);
                    String script = " if redis.call('get', KEYS[1])  == ARGV[1]  then " + " return redis.call('expire', KEYS[1], ARGV[2]) " + " else return '0' end ";
                    // 设置参数
                    ArrayList args = new ArrayList<>(2);
                    args.add(requestId);
                    args.add(time);
                    DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
                    StringRedisTemplate redisTemplate = stringRedisTemplate;
                    redisTemplate.execute(redisScript, Arrays.asList(lockKey), args);
                } catch (InterruptedException e) {
                    return;
                }
            }
        });
    }
}